
from flask import Flask, request, render_template, jsonify, redirect, url_for
import pandas as pd
from scipy import stats
import os
from flask import make_response

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['ALLOWED_EXTENSIONS'] = {'xlsx', 'xls'}

os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # 检查请求中是否有文件
        if 'file' not in request.files:
            return jsonify({"error": "No file part"}), 400
        file = request.files['file']
        # 如果没有选择文件，浏览器也会提交一个没有文件名的空部分
        if file.filename == '':
            return jsonify({"error": "No selected file"}), 400
        if file and allowed_file(file.filename):
            file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
            file.save(file_path)

            df = pd.read_excel(file_path, sheet_name='Sheet1')

            # 判断是否执行正态分布检验或双样本T检验
            if 'test_type' not in request.form or request.form['test_type'] == '正态分布检验':
                # 正态分布检验
                if 'A' not in df.columns:
                    return jsonify({"error": "Excel文件中必须包含A列"}), 400
                data_A = df['A']
                stat, p_value = stats.shapiro(data_A.dropna())  # 丢弃NaN值
                rounded_p_value = round(p_value, 3)

                response_text = f"P值是: {rounded_p_value}\n"
                response_text += "符合正态分布" if rounded_p_value > 0.05 else "不符合正态分布"
            elif request.form['test_type'] == '双T验证':
                # 双样本T检验
                if 'A' not in df.columns or 'B' not in df.columns:
                    return jsonify({"error": "Excel文件中必须包含A列和B列"}), 400
                data_A = df['A']
                data_B = df['B']

                t_stat, p_value = stats.ttest_ind(data_A.dropna(), data_B.dropna())  # 丢弃NaN值
                rounded_p_value = round(p_value, 3)


                response_text = f"P值: {rounded_p_value}\n"
                alpha = 0.05
                response_text += "两个样本的均值存在显著差异" if rounded_p_value < alpha else "两个样本的均值不存在显著差异"
            elif request.form['test_type'] == 'Anova验证':
                # 双样本T检验
                if 'A' not in df.columns or 'B' not in df.columns or 'C' not in df.columns:
                    return jsonify({"error": "Excel文件中必须包含A列，B列和C列"}), 400
                data_A = df['A']
                data_B = df['B']
                data_C = df['C']

                # 使用SciPy进行基础ANOVA
                f_value, p_value = stats.f_oneway(data_A, data_B, data_C)
                rounded_p_value = round(p_value, 3)

                response_text = f"P值: {rounded_p_value}\n"
                alpha = 0.05
                response_text += "至少两个样本的均值存在显著差异" if rounded_p_value < alpha else "三个样本的均值都不存在显著差异"

            else:
                return jsonify({"error": "Invalid test type"}), 400

            # 创建响应对象
            response = make_response(response_text)
            response.headers['Content-Type'] = 'text/plain; charset=utf-8'
            return response, 200

    # 如果没有POST请求，则显示上传表单
    return render_template('upload.html')


if __name__ == '__main__':
    app.run(debug=True)